from rest_framework import serializers
from wechatpy import WeChatClient
from wechatpy.exceptions import WeChatClientException  # 添加此行导入异常类
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.validators import RegexValidator  # 修正导入路径
import time
import logging
import re

User = get_user_model()

class WeChatLoginSerializer(serializers.Serializer):
    code = serializers.CharField(
        required=True,
        help_text="微信临时登录凭证，通过wx.login()获取，有效期5分钟"
        # 移除RegexValidator，改用手动验证
    )

    def validate_code(self, code):
        # 去除前后空白字符
        original_code = code
        code = code.strip()
        
        # 记录code接收时间和格式信息
        current_timestamp = int(time.time())
        logger = logging.getLogger(__name__)
        
        # 1. 检查长度
        if len(code) != 33:
            logger.error(f"code长度验证失败: 原始长度={len(original_code)}, 去除空白后长度={len(code)}, code值={original_code}")
            raise serializers.ValidationError(f'code格式错误: 长度必须为33位（当前去除空白后为{len(code)}位）')
        
        # 2. 检查字符类型
        if not re.match(r'^[A-Za-z0-9]{33}$', code):
            # 找出无效字符
            invalid_chars = [c for c in code if not c.isalnum()]
            logger.error(f"code字符验证失败: 无效字符={invalid_chars}, code值={code}")
            raise serializers.ValidationError(f'code格式错误: 包含非字母数字字符 {invalid_chars}')
        
        logger.info(f"code格式验证通过: 长度={len(code)}, 接收时间={current_timestamp}")
        
        # 添加API调用前的时间戳和耗时计算
        api_call_start = int(time.time())
        logger.info(f"开始调用微信API: code={code}, 接收至调用耗时={api_call_start - current_timestamp}秒")
        
        # 初始化微信客户端
        client = WeChatClient(
            settings.WECHAT_APP_ID,
            settings.WECHAT_APP_SECRET
        )

        try:
            res = client.wxa.code_to_session(js_code=code)
        except WeChatClientException as e:
            # 解析微信API错误信息
            error_msg = str(e)
            error_code = getattr(e, 'errcode', None)
            # 记录完整异常信息
            logger.exception(f"微信API调用异常: code={code}, errcode={error_code}")
            # 记录详细错误日志以便排查
            logger.error(f"微信code验证失败: code={code}, 错误码={error_code}, 错误信息={error_msg}")
            # 根据错误类型提供更具体的提示
            if error_code == 40029:
                raise serializers.ValidationError(f'微信登录失败: 无效的code(可能已过期或被使用), code长度={len(code)}, 错误详情: {error_msg}')
            else:
                raise serializers.ValidationError(f'微信登录失败: {error_msg}')
        except Exception as e:
            logger.exception(f"微信登录未知异常: code={code}")
            raise serializers.ValidationError(f'登录处理失败: {str(e)}')

    def create(self, validated_data):
        wechat_info = self.context.get('wechat_info')
        openid = wechat_info.get('openid')

        # 查询或创建用户
        user, created = User.objects.get_or_create(
            username=openid,
            defaults={'password': User.objects.make_random_password()}
        )

        return user

class ChatSerializer(serializers.Serializer):
    prompt = serializers.CharField(required=True, max_length=2000)